const config = require('../util/config')
const log = require('../util/log')
const ChromeMng = require('./chromeMng1/ChromeMng')
const logger = require('log4js').getLogger()
const CDP = require('chrome-remote-interface')

const taobaoTabNum = 1

var chromePromises = [],
    taobaoPromises = [],
    jdPromises = [],
    wechatPromises = []

var storage = {}

if (config.domain == '') {
    taobaoPromises.push(new Promise((resolve, reject) => {
            var chrome = new ChromeMng({
                port: 9222,
                type: 'taobao',
                username: config.local.taobaoUsername,
                password: config.local.taobaoPassword,
                store(obj) {
                    storage['1'] = storage['1'] || {}
                    for (var key in obj) {
                        storage['1'][key] = obj[key]
                    }
                },
                resolve() {
                    resolve(chrome)
                    return

                    CDP.List({
                        port: 9222
                    }).then(result => {
                        CDP.Activate({
                            port: 9222,
                            id: result[0].id
                        })
                        var mainTabId = result[0].id
                        var i = 1
                        for (; i < taobaoTabNum && i < result.length; i++) {
                            let j = i + ''
                            var chrome = new ChromeMng({
                                port: 9222,
                                target: result[i].id,
                                type: 'taobao',
                                username: config.local.taobaoUsername,
                                password: config.local.taobaoPassword,
                                resolve() {
                                    taobaoPromises.push(Promise.resolve(chrome))
                                },
                                reject() {},
                                store(obj) {
                                    storage[j] = storage[j] || {}
                                    for (var key in obj) {
                                        storage[j][key] = obj[key]
                                    }
                                }
                            })
                        }
                        for (; i < taobaoTabNum; i++) {
                            let j = i + ''
                            CDP.New({
                                port: 9222
                            }).then(result => {
                                CDP.Activate({
                                    port: 9222,
                                    id: mainTabId
                                })
                                var chrome = new ChromeMng({
                                    port: 9222,
                                    target: result.id,
                                    type: 'taobao',
                                    username: config.local.taobaoUsername,
                                    password: config.local.taobaoPassword,
                                    resolve() {
                                        taobaoPromises.push(Promise.resolve(chrome))
                                    },
                                    reject() {},
                                    store(obj) {
                                        storage[j] = storage[j] || {}
                                        for (var key in obj) {
                                            storage[j][key] = obj[key]
                                        }
                                    }
                                })
                            })
                        }
                        for (; i < result.length; i++) {
                            CDP.Close({
                                port: 9222,
                                id: result[i].id
                            })
                        }
                    }, result => {
                        logger.error('[' + __filename + ':' + __line + ']', result)
                    })
                },
                reject() {}
            })
        }))
        // jdPromises.push(new Promise((resolve, reject) => {
        //     var chrome = new ChromeMng({
        //         port: 9223,
        //         type: 'jd',
        //         resolve() {
        //             resolve(chrome)
        //         },
        //         reject() {}
        //     })
        // }))
} else if (config.domain == 'zoro.site') {
    // chromePromises.push(new Promise((resolve, reject) => {
    //     var chrome = new ChromeMng({
    //         port: 9222,
    //         resolve() {
    //             resolve(chrome)
    //         }
    //     })
    // }))
}

function random(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) % (max - min + 1) + min
}

exports.getTaobaoKeyWords = obj => {
    return new Promise((resolve, reject) => {
        var idx = random(0, taobaoPromises.length - 1)
        taobaoPromises[idx] = new Promise((chromeResolve, chromeReject) => {
            taobaoPromises[idx].then(chromrResult => {
                chromrResult.getTaobaoKeyWords(obj).then(result => {
                    resolve(result)
                    chromeResolve(chromrResult)
                }, result => {
                    reject(result)
                    chromeResolve(chromrResult)
                })
            }, result => {
                reject()
                logger.error('[' + __filename + ':' + __line + ']', result)
            })
        })
    })
}

exports.getTaobaoItems = obj => {
    return new Promise((resolve, reject) => {
        var idx = random(0, taobaoPromises.length - 1)
        taobaoPromises[idx] = new Promise((chromeResolve, chromeReject) => {
            taobaoPromises[idx].then(chromrResult => {
                chromrResult.getTaobaoItems(obj).then(result => {
                    resolve(result)
                    chromeResolve(chromrResult)
                }, result => {
                    reject(result)
                    chromeResolve(chromrResult)
                })
            }, result => {
                reject()
                logger.error('[' + __filename + ':' + __line + ']', result)
            })
        })
    })
}

exports.loginTaobao = obj => {
    var promises = []
    for (var i = 0; i < taobaoPromises.length; i++) {
        promises.push(new Promise((resolve, reject) => {
            taobaoPromises[i] = new Promise((chromeResolve, chromeReject) => {
                taobaoPromises[i].then(chromeResult => {
                    chromeResult.loginTaobao().then(result => {
                        resolve()
                        chromeResult.store({
                            qrcode: ''
                        })
                        chromeResolve(chromeResult)
                    }, result => {
                        if (result) {
                            logger.error('[' + __filename + ':' + __line + ']', result)
                            if (result.message) {
                                logger.error('[' + __filename + ':' + __line + ']', result.message)
                                if (result.message.indexOf('not open') != -1) {
                                    chromeResult.connect()
                                }
                            }
                        }
                        reject(config.local.taobaoUsername + '登录淘宝联盟失败')
                        chromeResult.store({
                            qrcode: ''
                        })
                        chromeResolve(chromeResult)
                    })
                }, result => {
                    logger.error('[' + __filename + ':' + __line + ']', result)
                    reject()
                })
            })
        }))
    }
    return new Promise((resolve, reject) => {
        Promise.all(promises).then(result => {
            resolve()
        }, result => {
            reject()
        })
    })
}

exports.getTaobaoAdvLink = obj => {
    return new Promise((resolve, reject) => {
        var idx = random(0, taobaoPromises.length - 1)
        taobaoPromises[idx] = new Promise((chromeResolve, chromeReject) => {
            taobaoPromises[idx].then(chromeResult => {
                chromeResult.getTaobaoAdvLink(obj).then(result => {
                    resolve(result)
                    chromeResolve(chromeResult)
                }, result => {
                    reject(result)
                    chromeResolve(chromeResult)
                })
            }, result => {
                reject()
                logger.error('[' + __filename + ':' + __line + ']', result)
            })
        })
    })
}

exports.checkLoginTaobao = obj => {
    var promises = []
    for (var i = 0; i < chromeMngs.length; i++) {
        promises.push(new Promise((resolve, reject) => {
            taobaoPromises[i] = new Promise((chromeReslve, chromeReject) => {
                taobaoPromises[i].then(chromeResult => {
                    chromeResult.checkLoginTaobao().then(result => {
                        resolve(result ? 1 : -1)
                        chromeReslve(chromeResult)
                    }, result => {
                        resolve(0)
                        chromeReslve(chromeResult)
                    })
                }, result => {
                    reject()
                    logger.error('[' + __filename + ':' + __line + ']', result)
                })
            })
        }))
    }
    return new Promise((resolve, reject) => {
        Promise.all(promises).then(result => {
            resolve(result)
        })
    })
}

exports.loginJd = obj => {
    obj = obj || {}
    obj.idx = obj.idx || 0
    if (obj.idx == jdPromises.length) {
        return Promise.resolve()
    }
    return new Promise((resolve, reject) => {
        jdPromises[obj.idx] = new Promise((chromeResolve, chromeReject) => {
            jdPromises[obj.idx].then(chromeResult => {
                chromeResult.loginJd(obj).then(result => {
                    obj.idx++;
                    exports.loginJd(obj).then(result => {
                        resolve(result)
                    }, result => {
                        reject(result)
                    })
                    chromeResolve(chromeResult)
                }, result => {
                    reject(result)
                    chromeResolve(chromeResult)
                })
            }, result => {
                if (result)
                    logger.error('[' + __filename + ':' + __line + ']', result)
                reject()
            })
        })
    })
}

exports.getJdAdvLink = obj => {
    return new Promise((resolve, reject) => {
        var idx = random(0, jdPromises.length - 1)
        jdPromises[idx] = new Promise((chromeResolve, chromeReject) => {
            jdPromises[idx].then(chromeResult => {
                chromeResult.getJdAdvLink(obj).then(result => {
                    resolve(result)
                    chromeResolve(chromeResult)
                }, result => {
                    reject(result)
                    chromeResolve(chromeResult)
                })
            }, result => {
                if (result)
                    logger.error('[' + __filename + ':' + __line + ']', result)
                reject(result)
            })
        })
    })
}

exports.getJdItems = obj => {
    return new Promise((resolve, reject) => {
        var idx = random(0, jdPromises.length - 1)
        jdPromises[idx] = new Promise((chromeResolve, chromeReject) => {
            jdPromises[idx].then(chromeResult => {
                chromeResult.getJdItems(obj).then(result => {
                    resolve(result)
                    chromeResolve(chromeResult)
                }, result => {
                    reject(result)
                    chromeResolve(chromeResult)
                })
            }, result => {
                reject()
                logger.error('[' + __filename + ':' + __line + ']', result)
            })
        })
    })
}

exports.checkLoginJd = obj => {
    return new Promise((resolve, reject) => {
        var idx = random(0, jdPromises.length - 1)
        jdPromises[idx] = new Promise((chromeResolve, chromeReject) => {
            jdPromises[idx].then(chromeResult => {
                chromeResult.checkLoginJd(obj).then(result => {
                    resolve(result)
                    chromeResolve(chromeResult)
                }, result => {
                    reject(result)
                    chromeResolve(chromeResult)
                })
            }, result => {
                reject()
                logger.error('[' + __filename + ':' + __line + ']', result)
            })
        })
    })
}

exports.getTaobaoBill = obj => {
    return new Promise((resolve, reject) => {
        var idx = random(0, taobaoPromises.length - 1)
        taobaoPromises[idx] = new Promise((chromeResolve, chromeReject) => {
            taobaoPromises[idx].then(chromeResult => {
                chromeResult.loginTaobao().then(async result => {
                    //chromeMng.checkTaobaoLogin().then(async result => {
                    //if (!result) {
                    //    log('未登录淘宝联盟，释放chrome')
                    //    chromeMng.busy = false
                    //    reject('未登录淘宝联盟，释放chrome')
                    //   return
                    //}
                    chromeResult.taobaoBill = []
                    chromeResult.getTaobaoBillResolve = taobaoBill => {
                        // logger.error('[' + __filename + ':' + __line + ']', 'get taobao bill resolve')
                        taobaoBill.forEach(item => {
                            item.fromUsername = config.local.taobaoUsername
                        })
                        resolve(taobaoBill)
                        chromeResolve(chromeResult)
                    }
                    chromeResult.getTaobaoBillReject = result => {
                        if (result)
                            logger.error('[' + __filename + ':' + __line + ']', result)
                        reject(result)
                        chromeResolve(chromeResult)
                    }
                    chromeResult.getTaobaoBillTimeout = setTimeout(() => {
                        chromeResult.getTaobaoBillResolve = () => {}
                        chromeResult.getTaobaoBillReject = () => {}
                        logger.error('[' + __filename + ':' + __line + ']', '获取淘宝订单超时，释放chrome')
                        reject('获取淘宝订单超时，释放chrome')
                        chromeResolve(chromeResult)
                    }, 30000)
                    const {
                        Network,
                        Page,
                        DOM,
                        Runtime,
                        Emulation
                    } = chromeResult.client
                    var startTime = require('../../lib/formatDate')(new Date(new Date().getTime() - 15 * 86400 * 1000), 'yyyy-MM-dd')
                    var endTime = require('../../lib/formatDate')(new Date(), 'yyyy-MM-dd')
                    var url = 'https://pub.alimama.com/manage/effect/overview_orders.htm?pageNo=1&queryType=2&jumpType=0&positionIndex=&startTime=' + startTime + '&endTime=' + endTime
                    logger.debug('[' + __filename + ':' + __line + ']', '抓取' + url)
                    await Page.navigate({
                        url
                    })
                }, result => {
                    // if (result)
                    logger.error('[' + __filename + ':' + __line + ']', result)
                    reject(result)
                    chromeResolve(chromeResult)
                })
            }, result => {
                // if (result)
                logger.error('[' + __filename + ':' + __line + ']', result)
                reject(result)
            })
        })
    })
}

exports.getJdBill = obj => {
    return new Promise((resolve, reject) => {
        if (jdPromises.length == 0) {
            reject()
            return
        }
        var idx = random(0, jdPromises.length - 1)
        jdPromises[idx] = new Promise((chromeResolve, chromeReject) => {
            jdPromises[idx].then(chromeResult => {
                chromeResult.checkLoginJd().then(result => {
                    if (!result) {
                        reject('未登录京东联盟，释放chrome')
                        chromeResolve(chromeResult)
                        return
                    }
                    chromeResult.jdBill = []
                    chromeResult.getJdBillResolve = result => {
                        resolve(result)
                        chromeResolve(chromeResult)
                    }
                    chromeResult.getJdBillReject = result => {
                            reject(result)
                            chromeResolve(chromeResult)
                        }
                        // setTimeout(async () => {
                        //     if (!chromeMng.busy) {
                        //         return
                        //     }
                        //     var {result} = await Runtime.evaluate({expression: 'location.href'})
                        //     if (!result.value.startsWith('https://media.jd.com/rest/report/detail')) {
                        //         return
                        //     }
                        //     log('获取京东联盟订单，释放chrome')
                        //     chromeMng.busy = false
                        // }, 60000)
                    const {
                        Network,
                        Page,
                        DOM,
                        Runtime,
                        Emulation
                    } = chromeResult.client;
                    Page.navigate({
                        url: 'https://media.jd.com/rest/report/detail'
                    })
                }, result => {
                    reject(result)
                    chromeResolve(chromeResult)
                })
            }, result => {
                reject()
                logger.error('[' + __filename + ':' + __line + ']', result)
            })
        })
    })
}

exports.getTaobaoLoginQrcodes = () => {
    return new Promise((resolve, reject) => {
        var qrcodes = []
        for (var key in storage) {
            if (storage[key].qrcode)
                qrcodes.push({
                    username: storage[key].username,
                    qrcode: storage[key].qrcode
                })
        }
        resolve(qrcodes)
    })
}

exports.getRedirectLink = obj => {
    return new Promise((resolve, reject) => {
        var len = chromePromises.length + taobaoPromises.length
        if (len == 9) {
            logger.error('[' + __filename + ':' + __line + ']', 'no chrome')
            reject()
        }
        var idx = random(0, len - 1)
        var promise = new Promise((chromeResolve, chromeReject) => {
            var _promise = null
            if (idx < chromePromises.length)
                _promise = chromePromises[idx]
            idx -= chromePromises.length
            if (idx < taobaoPromises.length)
                _promise = taobaoPromises[idx]

            _promise.then(chromeResult => {
                chromeResult.getRedirectLink(obj).then(result => {
                    resolve(result)
                    chromeResolve(chromeResult)
                }, result => {
                    if (result) {
                        logger.error('[' + __filename + ':' + __line + ']', obj.link, result)
                        if (result.message == 'not opened') {
                            chromeResult.connect()
                        }
                    }
                    reject(result)
                    chromeResolve(chromeResult)
                })
            }, result => {
                if (result)
                    logger.error('[' + __filename + ':' + __line + ']', result)
                reject(result)
            })
        })

        if (idx < chromePromises.length)
            chromePromises[idx] = promise
        idx -= chromePromises.length
        if (idx < taobaoPromises.length)
            taobaoPromises[idx] = promise
    })
}

exports.getWechatLoginQrcodes = () => {
    return new Promise((resolve, reject) => {
        var qrcodes = []
        var promises = []
        for (var i = 0; i < wechatPromises.length; i++) {
            promises.push(new Promise((resolve, reject) => {
                wechatPromises[i] = new Promise((chromeResolve, chromeReject) => {
                    wechatPromises[i].then(chromeResult => {
                        chromeResult.qrcode && qrcodes.push(chromeResult.qrcode)
                        resolve()
                        chromeResolve(chromeResult)
                    }, result => {
                        reject()
                        logger.error('[' + __filename + ':' + __line + ']', result)
                    })
                })
            }))
        }
        Promise.all(promises).then(result => {
            resolve(result)
        })
    })
}

exports.sendWechatMsg = obj => {
    wechatPromises[obj.from] = new Promise((chromeResolve, chromeReject) => {
        wechatPromises[obj.from].then(chromeResult => {
            chromeResult.send({
                who: obj.to,
                what: 'hi'
            })
            chromeResolve(chromeResult)
        }, result => {
            logger.error('[' + __filename + ':' + __line + ']', result)
        })
    })
}

exports.loginWechat = obj => {
    var promises = []
    for (var i = 0; i < wechatPromises.length; i++) {
        promises.push(new Promise((resolve, reject) => {
            wechatPromises[i] = new Promise((chromeResolve, chromeReject) => {
                wechatPromises[i].then(chromeResult => {
                    chromeResult.loginWechat().then(result => {
                        resolve()
                        chromeResolve(chromeResult)
                    }, result => {
                        resolve()
                        chromeResolve(chromeResult)
                    })
                }, result => {
                    reject()
                    logger.error('[' + __filename + ':' + __line + ']', result)
                })
            })
        }))
    }
    return new Promise((resolve, reject) => {
        Promise.all(promises).then(result => {
            resolve()
        })
    })
}

exports.getCode = obj => {
    // for (var i = 0; i < chromeMngs.length; i++) {
    //     if (chromeMngs[i].code && chromeMngs[i].codeRequestId) {
    //         return new Promise(resolve => {
    //             resolve({
    //                 code: chromeMngs[i].code,
    //                 codeRequestId: chromeMngs[i].codeRequestId
    //             })
    //         })
    //     }
    // }
    // for (var i = 0; i < jdChromeMngs.length; i++) {
    //     if (jdChromeMngs[i].code && jdChromeMngs[i].codeRequestId) {
    //         return new Promise(resolve => {
    //             resolve({
    //                 code: jdChromeMngs[i].code,
    //                 codeRequestId: jdChromeMngs[i].codeRequestId
    //             })
    //         })
    //     }
    // }
    // return new Promise((resolve, reject) => {
    //     resolve({
    //         code: '',
    //         codeRequestId: ''
    //     })
    // })
    return Promise.resolve({
        code: '',
        codeRequestId: ''
    })
}

// exports.submitCode = obj => {
//     obj = obj || {}
//     obj.codeRequestId = obj.codeRequestId || ''
//     for (var i = 0; i < chromeMngs.length; i++) {
//         if (obj.codeRequestId == chromeMngs[i].codeRequestId) {
//             chromeMngs[i].codeText = obj.codeText
//             return new Promise(resolve => {
//                 resolve()
//             })
//         }
//     }
//     for (var i = 0; i < jdChromeMngs.length; i++) {
//         if (obj.codeRequestId == jdChromeMngs[i].codeRequestId) {
//             jdChromeMngs[i].codeText = obj.codeText
//             return new Promise(resolve => {
//                 resolve()
//             })
//         }
//     }
//     return new Promise((resolve, reject) => {
//         resolve()
//     })
// }